package com.helloandroid.ext

import com.cy.game.CyInfo
import com.helloandroid.tools.GUtils
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils
import com.helloandroid.vo.*
import com.jf.game.JFInfo
import com.zp.game.ZhuanPanInfo
import org.json.JSONObject
import java.lang.Exception

class ParseResult(val err: Int, val obj: Any) {
    val msg: String
        get() = obj as String
}

fun <T> JSONObject.tryParseJson(parseMethod: JSONObject.() -> T, defValue: Any? = null): ParseResult {
    val err = getInt(GUtils.KeyErr)
    return if (err == 0) {
        if (has("json")) {
            val dataObj = JSONObject(getString(GUtils.KeyData))
            ParseResult(err, parseMethod.invoke(dataObj) as Any)
        } else {
            if (has(GUtils.KeyData)) {
                ParseResult(err, parseMethod.invoke(getJSONObject(GUtils.KeyData)) as Any)
            } else {
                if (defValue != null) {
                    ParseResult(err, defValue)
                } else {
                    ParseResult(err, Unit)
                }
            }
        }
    } else {
        val msg = getString(GUtils.KeyMsg)
        ParseResult(err, msg)
    }
}


// customKey  用于处理 形如 {err:0,target:int} 这样的
//
fun <T> JSONObject.process(parseMethod: JSONObject.() -> T, defValue: Any? = null): ParseResult {
    return try {
        val parseResult = tryParseJson(parseMethod, defValue)
        parseResult
    } catch (ex: Exception) {
        MyLog.elog("解析错误!")
        ParseResult(1000, "解析错误")
    }
}

//MyLog.elog("解析错误!")
//return ParseResult(err , "解析错误")


fun JSONObject.parseUser(): User {

    val user_id = getInt("user_id")
    val coin = getInt("coin")
    val money = getInt("money")
    val tx_count = getInt("tx_count")

    val stampStr1 = getString("tx_time_stamp")
    val tx_time_stamp = MyTimeUtils.transformTimeByZone(stampStr1)

    val bs = getInt("bs")
    val bs_sys = getInt("bs_sys")
    val bs_target = getInt("bs_target")
    val signed_count = getInt("signed_count")

    val stampStr2 = getString("sign_time_stamp")
    val sign_time_stamp = MyTimeUtils.transformTimeByZone(stampStr2)

    val wxId = getString("wx_id")
    val wx_id = if (wxId.toString() == "null") "" else wxId

    val wxData = getString("wx_data")
    val wx_name: String
    val wx_sex: Int
    val wx_icon: String
    if (wxData == "null") {
        wx_name = ""
        wx_sex = 0
        wx_icon = ""
    } else {
        val wxInfoObj = JSONObject(wxData)
        wx_name = wxInfoObj.getString("nickname")
        wx_sex = wxInfoObj.getInt("sex")
        wx_icon = wxInfoObj.getString("headimgurl")
    }

//    val wxName = getString("wx_name")
//    val wx_name = if (wxName.toString() == "null") "" else wxName
//
//    val wx_sex = getInt("wx_sex")
//
//    val wxIcon = getString("wx_icon")
//    val wx_icon = if (wxIcon.toString() == "null") "" else wxIcon

    return User(
            user_id = user_id,
            coin = coin,
            money = money,
            tx_count = tx_count,
            tx_time_stamp = tx_time_stamp,
            bs = bs,
            bs_sys = bs_sys,
            bs_target = bs_target,
            signed_count = signed_count,
            sign_time_stamp = sign_time_stamp,
            wx_id = wx_id,
            wx_name = wx_name,
            wx_sex = wx_sex,
            wx_icon = wx_icon
    )
}

fun JSONObject.parseBoardInfo(): BoardInfo {
    val cointime1 = getLong("cointime1")
    val cointime2 = getLong("cointime2")
    val cointime3 = getLong("cointime3")
    val daily_money_state = getInt("daily_money_state")
    val bsCount = getInt("award_id") // 后面修改了 参数意义
    val firstused = getInt("firstused")
    return BoardInfo(cointime1 = cointime1, cointime2 = cointime2, cointime3 = cointime3, bsCount = bsCount, dailyCoinState = daily_money_state, firstUsed = firstused)
}

fun JSONObject.parseSignResponse(): SignResponse {

    val totoal = getInt("coin")
    val added = getInt("addCoin")
    val signed_count = getInt("signed_count")
    val signTimeMs = MyTimeUtils.transformTimeByZone(getString("sign_time_stamp"))
    return SignResponse(
            total = totoal,
            added = added,
            signedCount = signed_count,
            signTimeMs = signTimeMs
    )
}


fun JSONObject.parseZhuanPanInfo(): ZhuanPanInfo {
    val oppoX2 = getInt("OppoX2")
    val vivoX60 = getInt("VivoX60")
    val xiaoMi10Pro = getInt("XiaoMi10Pro")
    val hwMate40Pro = getInt("hwMate40Pro")
    val iphone12Pro = getInt("iphone12Pro")

    val restcount = getInt("restcount")
    val usedcount = getInt("usedcount")

    val jsonArr = getJSONArray("awardstate")
    val awardstate = ArrayList<Int>()
    for (i in 0 until jsonArr.length()) {
        awardstate.add(jsonArr.getInt(i))
    }
    return ZhuanPanInfo(
            resetCount = restcount,
            usedCount = usedcount,
            iphone12Pro = iphone12Pro,
            hwMate40 = hwMate40Pro,
            xiaomi10 = xiaoMi10Pro,
            oppoX = oppoX2,
            vivoX60 = vivoX60,
            awardStateLst = awardstate
    )
}

fun JSONObject.parseZaoWanInfo(): ZaoWan {
    val wanExecuted = getInt("wanExecuted")
    val zaoExecuted = getInt("zaoExecuted")
    return ZaoWan(zaoExecuted = zaoExecuted, wanExecuted = wanExecuted)
}

//fun JSONObject.parseCoinAward():CoinAward{
//    val coin = getInt("coin")
//    return CoinAward(coin)
//}

fun JSONObject.parseCoinResponse(): CoinResponse {
    val total = getInt("coin")
    val added = getInt("addCoin")
    return CoinResponse(total, added)
}

fun JSONObject.parseHeShuiInfo(): HeShuiInfo {
    val w1 = getInt("w1")
    val w2 = getInt("w2")
    val w3 = getInt("w3")
    val w4 = getInt("w4")
    val w5 = getInt("w5")
    val w6 = getInt("w6")
    val w7 = getInt("w7")
    val w8 = getInt("w8")
    return HeShuiInfo(w1, w2, w3, w4, w5, w6, w7, w8)
}

fun JSONObject.parseChiFanInfo(): ChiFanInfo {
    val wucan = getInt("wucan")
    val wancan = getInt("wancan")
    val xiaoye = getInt("xiaoye")
    val zaocan = getInt("zaocan")
    val xiawucha = getInt("xiawucha")
    return ChiFanInfo(zaocan, wucan, xiawucha, wancan, xiaoye)
}

fun JSONObject.parseSportInfo(): MeiRiYunDongInfo {

    val map = HashMap<String, SportItem>()

    // 原地跳
    val yuanditiao = getJSONObject("yuanditiao")
    map[SportName.Yuanditiao] = SportItem(yuanditiao.getInt("state"), yuanditiao.getLong("start"))

    // 乒乓球
    val pingpangqiu = getJSONObject("pingpangqiu")
    map[SportName.Pingpangqiu] = SportItem(pingpangqiu.getInt("state"), pingpangqiu.getLong("start"))

    // 踢足球
    val tizuqiu = getJSONObject("tizuqiu")
    map[SportName.Tizuqiu] = SportItem(tizuqiu.getInt("state"), tizuqiu.getLong("start"))

    // 打篮球
    val dalanqiu = getJSONObject("dalanqiu")
    map[SportName.Dalanqiu] = SportItem(dalanqiu.getInt("state"), dalanqiu.getLong("start"))

    // 跑步
    val paobu = getJSONObject("paobu")
    map[SportName.Paobu] = SportItem(paobu.getInt("state"), paobu.getLong("start"))

    // 健身操
    val jianshencao = getJSONObject("jianshencao")
    map[SportName.Jianshencao] = SportItem(jianshencao.getInt("state"), jianshencao.getLong("start"))

    return MeiRiYunDongInfo(map)
}

fun JSONObject.parseEmpty() = Unit

fun JSONObject.parseBsInfo(): BsInfo {
    val bs = getInt("bs")
    val state = getInt("bs_daka_status")
    val coin = getInt("awardCoin")
    return BsInfo(state = state, coin = coin, bs = bs)
}

fun JSONObject.parseZhuanPanResponse(): ZhuanPanResponse {
    val result_id = getInt("result_id")
    val count = getInt("count")
    val addcount = getInt("addcount")
    val restcount = getInt("restcount")
    val usedcount = getInt("usedcount")
    return ZhuanPanResponse(
            result_id = result_id,
            count = count,
            addcount = addcount,
            restcount = restcount,
            usedcount = usedcount
    )
}


fun JSONObject.parseTaskInfo(): TaskInfo {

    val firstTx = getJSONObject("first_tx").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        FirstTiXian(state,count)
    }

    val dailyBs = getJSONObject("daily_bushu").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyBuShu(state,count)
    }

    val bindWx = getJSONObject("bind_wx").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        BindWx(state,count)
    }

    val dailyShare = getJSONObject("daily_share").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyShare(state,count)
    }

    //
    val dailyHongBaoMatch = getJSONObject("daily_hbmatch").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyHongBaoMatch(state,count)
    }

    val dailySport = getJSONObject("daily_sport").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailySport(state,count)
    }


    //----- state and count
    val dailyVideo = getJSONObject("daily_video").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyVideo(state, count)
    }

    val dailyHeShui = getJSONObject("daily_heshui").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyHeShui(state, count)
    }

    val dailyZaoWan = getJSONObject("daily_zaowan").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyZaoWan(state, count)
    }

    val dailyChiFan = getJSONObject("daily_chifan").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyChiFan(state, count)
    }

    val dailyZhuanPan = getJSONObject("daily_zhuanpan").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyZhuanPan(state, count)
    }

    val hongBaoYu = getJSONObject("daily_hongbaoyu").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyHongBaoYu(state, count)
    }

    val chengYu = getJSONObject("daily_chengyu").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyChengYu(state, count)
    }

    val jifu = getJSONObject("daily_niudan").let {
        val state = it.getInt("state")
        val count = it.getInt("count")
        DailyJiFuZi(state, count)
    }

    return TaskInfo(
            firstTx = firstTx,
            bushu = dailyBs,
            bindwx = bindWx,
            share = dailyShare,
            hbMatch = dailyHongBaoMatch,
            sport = dailySport,
            video = dailyVideo,
            heShui = dailyHeShui,
            zaoWan = dailyZaoWan,
            chiFan = dailyChiFan,
            zhuanPan = dailyZhuanPan,
            hongBaoYu = hongBaoYu,
            chengYu = chengYu,
            jifuzi = jifu
    )
}


fun JSONObject.parseZpExtraAward(): ZpExtraAward {
    val total = getInt("coin")
    val added = getInt("addCoin")
    return ZpExtraAward(total = total, added = added)
}


fun JSONObject.parseChangeTarget(): Int {
    return getInt("target")
}


fun JSONObject.parseCyInfo(): CyInfo {
    val power = getInt("power")
    val curlevel = getInt("curlevel")
    val tipcount = getInt("tipcount")
    val lastpower_time = getLong("lastpower_time")

    var totallevel = getInt("totallevel")
    if (totallevel < 1) totallevel = 1300

    return CyInfo(
            totalLevel = totallevel,
            curLevel = curlevel,
            power = power,
            tipCount = tipcount,
            lastRepowerMs = lastpower_time
    )
}

fun JSONObject.parsePower(): Int = getInt("power")

fun JSONObject.parseHongBaoYu(): HbyInfo {
    val count = getInt("count")
    val lastTimeMs = getLong("lasttime")
    return HbyInfo(lastTimeMs = lastTimeMs, count = count)
}

fun JSONObject.parseSyncResponse(): Boolean = getBoolean("targetOK")

fun JSONObject.parseCyHintResponse(): Int = getInt("tipcount")

fun JSONObject.parseTaskReportResponse(): TaskReportResponse {
    val count = getInt("count")
    val state = getInt("state")
    return TaskReportResponse(count, state)
}

fun JSONObject.parseHbyAwardResponse(): HbyAwardResponse {
    val count = getInt("count")
    val added = getInt("addCoin")
    val total = getInt("coin")
    return HbyAwardResponse(added, total, count)
}

//----------------------------------------------
//
fun JSONObject.parseTxRecord():ParseResult{
    val err = getInt(GUtils.KeyErr)

    // data 是 array
    if (err == 0){
         val dataArr = getJSONArray(GUtils.KeyData)
        var lst = ArrayList<TxItem>()
        if (dataArr.length() > 0){
            for (i in 0 until dataArr.length()){
                val itemObj = dataArr.getJSONObject(i)
                val amount = itemObj.getInt("amount")
                val timeStamp = MyTimeUtils.transformTimeByZone(itemObj.getString("time_stamp"))
                lst.add(TxItem(amount,timeStamp))
            }
        }
        return ParseResult(0,TxInfo(lst))
    }else{
        return ParseResult(err,getString("msg"))
    }
}

fun JSONObject.parseCoinAndMoney():CoinAndMoney{
    val coin = getInt("coin")
    val money = getInt("money")
    return CoinAndMoney(coin,money)
}


fun JSONObject.parseJFInfo():JFInfo{
    val fu = getInt("fu")
    val lu = getInt("lu")
    val shou = getInt("shou")
    val xi = getInt("xi")
    val cai = getInt("cai")
    val restCount = getInt("restcount")
    return JFInfo(fu, lu, shou, xi, cai, restCount)
}




fun JSONObject.parseJFAwardResponse():JFAwardResponse{
    val count = getInt("count")
    val result_id = getInt("result_id")
    val restcount = getInt("restcount")
    return JFAwardResponse(
            count,
            result_id,
            restcount)
}


//------------------------------------------------------
// 避免解析错误
fun JSONObject.tryGetString(key:String):String{
    return try {
        getString(key)
    }catch (e:Exception){
        ""
    }
}

fun JSONObject.tryGetInt(key:String):Int{
    return try {
        getInt(key)
    }catch (e:Exception){
        0
    }
}

